package com.csst.services.coreService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import net.sf.json.JSONObject;

import com.csst.business.action.UserAction;
import com.csst.popular.api.MenuAPI;
import com.csst.popular.bean.BaseResult;
import com.csst.popular.bean.xmlmessage.XMLImageMessage;
import com.csst.popular.bean.xmlmessage.XMLNewsMessage;
import com.csst.popular.bean.xmlmessage.XMLNewsMessage.Article;
import com.csst.popular.bean.xmlmessage.XMLTextMessage;
import com.csst.services.Thread.TokenThread;
import com.csst.services.common.MessageUtil;	
import com.csst.services.util.Bus;
import com.csst.services.util.Common;
import com.csst.services.util.Location;
import com.csst.services.util.Weather;


/** 
 * 核心服务类 
 *  
*
 * @date 2013-05-20 
 */  
public class CoreService {  
	private static String basePath;
    /** 
     * 处理微信发来的请求 
     *  
     * @param request 
     * @return 
     * @throws Exception  
     */  
    public static String processRequest(HttpServletRequest request) throws Exception {  
    	basePath = request.getScheme()+"://"+request.getServerName()+"/";
        String respMessage = null;  
            // 默认返回的文本消息内容测色测试
            String respContent = "功夫梦·中国，联系电话：0316-5121586\ue428";  
            // xml请求解析  
            Map<String, String> requestMap = MessageUtil.parseXml(request);  
            // 发送方帐号（open_id）  
            String fromUserName = requestMap.get("FromUserName");  
            // 公众帐号  
            String toUserName = requestMap.get("ToUserName");  
            // 消息类型  
            String msgType = requestMap.get("MsgType");  
            //消息内容1
           String msgContent = requestMap.get("Content");
           //自定义菜单推送的key
           String EventKey = requestMap.get("EventKey");
            // 文本消息  
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
            	if("官网".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getHomePage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("简介".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getAboutUsPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("动态".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getNewsPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("服务".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getProductPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("相册".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getPhotoPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("预约".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getOrderPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("留言".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getMessagePage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("会员".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getMemberPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("活动".equalsIgnoreCase(msgContent)){
            		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getGamesPage(fromUserName));
                    return xmlnewMessage.toXML();
            	}else  if("联系".equalsIgnoreCase(msgContent)){
            		/*XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getMemberPage(fromUserName));
                    return xmlnewMessage.toXML();*/
            	}
            	
             } // 图片消息  
           else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  
        	  /* String mediaId = requestMap.get("MediaId");
        	   XMLImageMessage xmlImgMes = new XMLImageMessage(fromUserName, toUserName, mediaId);
        	   return xmlImgMes.toXML();*/
            }  
            // 地理位置消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {  
            	/*System.out.println("获取用户地理信息了！");
            	String location_x = requestMap.get("Location_X");
            	String location_y = requestMap.get("Location_Y");
            	String scale = requestMap.get("Scale");
            	String label = requestMap.get("Label");
            	Location location = new Location();
                 XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, location.getLocation(location_x, location_y, scale, label));
                 return xmlnewMessage.toXML();*/
            }  
            // 链接消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
                /*respContent = "您发送的是链接消息！";  */
            }  
            // 音频消息  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
            	/* String recognition = requestMap.get("Recognition");
            	 String mediaID = requestMap.get("MediaID");
            	 String format = requestMap.get("Format");
                respContent = "您的语音识别结果是："+recognition; */
            }  
            // 事件推送  
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {  
                // 事件类型  
                String eventType = requestMap.get("Event"); 
                // 订阅  
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {  
                	 Common com = new Common();
                	 //关注获取用户信息：(成为微会员)
                	ServletContext servletContext = request.getSession().getServletContext();      
                	 WebApplicationContext wac = null;       
                	 wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);      
                	 UserAction useraction  = (UserAction) wac.getBean("userAction");
                	 useraction.saveMember(fromUserName);
                	 request.getSession().setAttribute("userOpenId", fromUserName);
                	 System.out.println(request.getSession().getAttribute("userOpenId"));
                	 XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getHomePage(fromUserName));
                     return xmlnewMessage.toXML();
                }  
                // 取消订阅  
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息  
                	 //删除微会员
                	 ServletContext servletContext = request.getSession().getServletContext();      
	            	 WebApplicationContext wac = null;       
	            	 wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);      
	            	 UserAction useraction  = (UserAction) wac.getBean("userAction");
	            	 boolean hasUser = useraction.getWuserByOpenId(fromUserName);
	            	 if(hasUser){
	            		 useraction.deleteWuser(fromUserName);
	            	 }
	            	 request.getSession().invalidate();
                }  
                else if (eventType.equalsIgnoreCase(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {  
                /*	System.out.println("获取用户地理信息了~~~====================================");
                	String location_x = requestMap.get("Latitude");
                	String location_y = requestMap.get("Longitude");
                	String location_Precision = requestMap.get("Precision");
                	respContent = "您当前坐标：\nx:"+location_x+",\ny:"+location_y+",\n精度:"+location_Precision;*/
                	// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息  
                }  
                // 自定义菜单点击事件  
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
                    // TODO 自定义菜单权没有开放，暂不处理该类消息  
                   if("官网".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getHomePage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("简介".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getAboutUsPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("动态".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getNewsPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("服务".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getProductPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("相册".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getPhotoPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("预约".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getOrderPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("留言".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getMessagePage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("会员".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getMemberPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("活动".equalsIgnoreCase(EventKey)){
                		XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getGamesPage(fromUserName));
                        return xmlnewMessage.toXML();
                	}else  if("联系".equalsIgnoreCase(EventKey)){
                		/*XMLNewsMessage xmlnewMessage = new XMLNewsMessage(fromUserName, toUserName, getMemberPage(fromUserName));
                        return xmlnewMessage.toXML();*/
                	}
                }
            }  
  
        XMLTextMessage textMes = new XMLTextMessage(fromUserName, toUserName, respContent);
        return textMes.toXML(); 
    }  
    
    /**
     * 得到主菜单
     * @return
     */
    public static String getMainMenu() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("\ue402您好，我是小哆啦，很高兴为您服务。").append("\n");
        buffer.append("请回复数字选择项目：").append("\n");  
        buffer.append("1  天气预报 \ue04a").append("\n");  
        buffer.append("2  位置服务 \ue209").append("\n");  
        buffer.append("3  测试页面").append("\n");  
        buffer.append("4  公交查询 \ue159").append("\n");  
        buffer.append("5  语音识别").append("\n");  
        buffer.append("6  微官网").append("\n");  
        buffer.append("7  在线预约").append("\n");  
        buffer.append("8  查看预约\ue428").append("\n");  
        buffer.append("9  酒店简介").append("\n");  
        buffer.append("10  酒店印象").append("\n");  
        buffer.append("回复“?”显示此帮助菜单，回复“@”进入欢迎页面。");  
        return buffer.toString();  
    } 
    
    public static List<Article> getHomePage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
		 Article article1 = new Article();  
        article1.setTitle("功夫梦·中国");  
        article1.setDescription("欢迎关注“功夫梦·中国”，我们的服务项目有少儿武术，成人散打，太极拳，由国家一级教练专业授课！请点击进入微官网");  
        article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
        System.out.println(openId);
        article1.setUrl(basePath+"/wpages/whome.jsp?openId="+openId); 
        homePage.add(article1);
		return homePage;
    }
    
    public static List<Article> getAboutUsPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("功夫梦·中国 简介");  
    	article1.setDescription("功夫梦·中国,打造少儿中国功夫第一品牌,由国家一级教练专业授课..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/wpages/aboutUS.jsp?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getNewsPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("最新动态");  
    	article1.setDescription("功夫梦·中国最新动态，让您实时关注到我们的最新活动等..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/news/getWNewslist.action?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getProductPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("服务内容");  
    	article1.setDescription("功夫梦·中国服务项目包括:1、  武术的礼仪,2、学习武术基本功一级武术中的精、气、神，提升人的潜在气质..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/wpages/product.jsp?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getPhotoPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("微相册");  
    	article1.setDescription("功夫梦·中国微相册发布武馆最近活动照片，以及学员联系风貌，让您在线参观..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/photo/getWPhotoGroupList.action?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getOrderPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("服务预约");  
    	article1.setDescription("我们的服务项目有少儿武术，成人散打，太极拳，您可以点击这里进入在线预约服务..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/company/getOrderPage.action?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getMessagePage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("微留言");  
    	article1.setDescription("把您的问题或者对功夫梦的印象写下来，我们会第一时间回复，点击进行留言..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/company/getMessagePage.action?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getMemberPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("微会员");  
    	article1.setDescription("第一次关注的用户，您可以在这里进行会员绑定，成为我们的微会员，还可以查看您的个人信息、预约订单、中奖信息等..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/user/toRegisterPage.action?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    public static List<Article> getGamesPage(String openId){
    	List<Article>  homePage = new ArrayList<Article>();
    	Article article1 = new Article();  
    	article1.setTitle("微活动");  
    	article1.setDescription("武馆会不定期举办大转盘、刮刮卡等抽奖活动，中奖用户将有机会获得我们的丰厚大礼，点击参加活动..");  
    	article1.setPicurl(basePath+"/wpages/images/aus.jpg");  
    	System.out.println(openId);
    	article1.setUrl(basePath+"/wpages/activity.jsp?openId="+openId); 
    	homePage.add(article1);
    	return homePage;
    }
    
    
    
    public static void main(String[] args) {
    	/*CoreService core = new CoreService();
    	HttpServletRequest request = null;
    	core.processRequest(request);*/
    	
	}
}  
